<template>
  <div>
    <Dialog
      ref="Drawer"
      @close="close"
      :loading="loading"
      @handleSave="handleSave"
      :title="title"
      :dialog="dialog"
    >
      <template #content>
        <el-form
          :model="ruleForm"
          size="small"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item
            label="登录账户"
            prop="name"
          >
            <el-input
              v-model="ruleForm.name"
              placeholder="请输入登录账户"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="登录密码"
            v-if="title == '新增用户'"
            prop="password"
          >
            <el-input
              :key="passwordType"
              ref="password"
              :type="passwordType"
              v-model="ruleForm.password"
              placeholder="请输入登录密码"
            >

            </el-input>
            <span
              class="show-pwd"
              @click="showPwd"
            >
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
          <el-form-item
            label="手机号码"
            prop="mobile"
          >
            <el-input
              v-model="ruleForm.mobile"
              placeholder="请输入手机号码"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="常用邮箱"
            prop="email"
          >
            <el-input
              v-model="ruleForm.email"
              placeholder="请输入常用邮箱"
            ></el-input>
          </el-form-item>
          <!-- <el-form-item
            label="用户类型"
            prop="type"
          >
            <el-select
              class="w100p"
              v-model="ruleForm.type"
              placeholder="请选择"
            >
              <el-option
                v-for="item in userTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item
            label="用户头像"
            prop="headPic"
          >
            <el-upload
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              accept=".gif,.jp2,.jpe,.jpeg,.jpg,.png"
              :file-list="fileList"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="ruleForm.headPic"
                :src="ruleForm.headPic"
                class="avatar"
              >
              <i
                v-else
                class="el-icon-plus avatar-uploader-icon"
              ></i>
            </el-upload>
          </el-form-item>
        </el-form>
      </template>
    </Dialog>
  </div>
</template>
<script>
import Dialog from "@/components/Dialog";
import * as settingApi from "@/api/setting1";
export default {
  components: {
    Dialog,
  },
  data() {
    const validateUserPhone = (rule, value, callback) => {
      if (value && !/^1(3|4|5|6|7|8|9)\d{9}$/.test(value)) {
        callback(new Error("电话有误，请重填"));
      } else {
        callback();
      }
    };
    const validateUserEmail = (rule, value, callback) => {
      if (value && !/^\w+@[a-z0-9]+\.[a-z]{2,4}$/.test(value)) {
        callback(new Error("填写的邮箱格式错误,请重新填写!"));
      } else {
        callback();
      }
    };
    return {
      dialog: false, //弹框
      rules: {
        //form表单非空校验
        name: [
          {
            required: true,
            message: "请输入登录账户",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入登录密码",
            trigger: "blur",
          },
        ],
        mobile: [
          {
            validator: validateUserPhone,
            trigger: "blur",
          },
        ],
        email: [
          {
            validator: validateUserEmail,
            trigger: "blur",
          },
        ],
      },
      ruleForm: {
        //表单提交
        id: "",
        name: "",
        password: "",
        mobile: "",
        type: "admin",
        headPic: "",
        email: "",
      },
      formLabelWidth: "100px", //表单label宽度
      loading: false, //表单提交按钮
      passwordType: "password",
      title: "",
      userTypeList: [
        // admin：监管管理员，hospital：医院管理员，staff：员工
        {
          label: "监管管理员",
          value: "admin",
        },
        {
          label: "医院管理员",
          value: "hospital",
        },
        {
          label: "员工",
          value: "staff",
        },
      ],
      fileList: [], //文件上传列表
    };
  },
  methods: {
    //弹框关闭
    close() {
      this.dialog = false;
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    //初始化弹框
    showModal(_type, _row) {
      this.dialog = true;
      this.ruleForm.id = ''
      this.$nextTick((_) => {
        this.$refs.ruleForm.resetFields();
        if (_type == "edit") {
          this.ruleForm = JSON.parse(JSON.stringify(_row));
          this.fileList = this.ruleForm.headPic
            ? [{ url: "this.ruleForm.headPic" }]
            : [];
          this.title = "编辑用户";
        } else {
          this.title = "新增用户";
        }
      });
    },
    handleAvatarSuccess(res, file) {
      this.ruleForm.headPic = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    //提交保存
    handleSave() {
      this.loading = true;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          settingApi
            .saveUser(this.ruleForm)
            .then((res) => {
              if (res && res.success) {
                this.loading = false;
                this.dialog = false;
                this.$emit("getDataList");
              } else {
                this.loading = false;
              }
            })
            .catch((e) => {
              this.loading = false;
            });
        } else {
          this.loading = false;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
$dark_gray: #889aa4;
.show-pwd {
  position: absolute;
  right: 10px;
  font-size: 16px;
  color: $dark_gray;
  cursor: pointer;
  user-select: none;
}
</style>
<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 108px;
  height: 108px;
  line-height: 108px;
  text-align: center;
}
.avatar {
  width: 108px;
  height: 108px;
  display: block;
}
</style>